package warthog.scangen;

import java.util.ArrayList;


public class Rule {
	final static private ArrayList<Rule> rules = new ArrayList<Rule>();
	final int line;
	final Regex re;
	final Node start;
	final Node end;
	boolean reached=false;
	final int id;
	String action;
	public Rule(int line, Regex re, String action) {
		this.line = line;
		this.re = re;
		this.action = action;
		start = new Node();
		end = Node.Terminal(this);
		re.connect(start, end);
		rules.add(this);
		this.id=rules.size();
	}
	public Rule compete(Rule that) {
		return (null==that || this.line < that.line) ? this : that;
	}
	public static void checkReached() {
		for (Rule r:rules) r.check();
	}
	private void check() {
		if (!reached) System.err.println(line+": Warning: Rule cannot be reached.");
	}
	void codeAction(StringBuilder w) {
		w.append("      case "+id+": /* line "+line+" */ "+action+" break;\n");
	}
	public static void writeActionCases(StringBuilder w) {
		for(Rule r:rules) r.codeAction(w);	}
}
